<?php
namespace frontend\modules\v1\models;

use common\models\Business;
use yii\base\Model;
use Yii;

/**
 * Password reset form
 */
class ResetPasswordForm extends Model
{
    public $account;
    public $code;
    public $password;
    public $repassword;

    /**
     * @var \common\models\Business
     */
    private $_business;

//    /**
//     * 构造方法校验数据是否存在
//     * @param array $username
//     * @param array $config
//     */
//    public function __construct($username, $config = [])
//    {
//        $this->username = $username;
//        if (empty($username) || !is_string($username)) {
//            throw new InvalidParamException('Password reset username cannot be blank.');
//        }
//        $this->_user = User::findByUsername($username);
//        if (!$this->_user) {
//            throw new InvalidParamException('username is not exist.');
//        }
//        parent::__construct($config);
//    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            /** 校验账号信息 */
            ['account', 'filter', 'filter' => 'trim'],
            ['account', 'required'],
            ['account', 'exist', 'targetClass' => '\common\models\Business', 'message' => '该手机号不存在.'],
            ['account', 'string', 'min' => 11, 'max' => 11],

            /** 验证码 必须 */
            ['code', 'filter', 'filter' => 'trim'],
            ['code', 'required'],

            /** 密码 必须 长度6-20*/
            ['password', 'required'],
            ['password', 'string', 'min' => 6, 'max' => 20],

            /** 校验密码是否相同 */
            ['repassword', 'compare', 'compareAttribute'=>'password', 'message'=>'两处输入的密码并不一致']
        ];
    }

    /**
     * Resets password.
     *
     * @return boolean if password was reset.
     */
    public function resetPassword()
    {
        /** 校验数据合法性 */
        if($this->validate()) {
            $this->_business = Business::findByAccount($this->account);
            $business = $this->_business;
            $business->setPassword($this->password);
            $business->removePasswordResetToken();
            return $business->save(false);
        }
        return null;
    }

    public function getBusiness(){
        return $this->_business;
    }
}
